import os
from pathlib import Path
from .redis_config import CACHE_REDIS_CONFIG, CELERY_REDIS_CONFIG, REDIS_URL

# 构建项目路径
BASE_DIR = Path(__file__).resolve().parent.parent

# 安全密钥，生产环境中需要保密
SECRET_KEY = 'django-insecure-your-secret-key-here'

# 调试模式，生产环境需要设置为False
DEBUG = True

# 允许所有主机请求
ALLOWED_HOSTS = ['*']

# 应用配置
INSTALLED_APPS = [
    # Django 内置应用
    'django.contrib.admin',  # 管理后台
    'django.contrib.auth',  # 认证系统
    'django.contrib.contenttypes',  # 内容类型
    'django.contrib.sessions',  # 会话
    'django.contrib.messages',  # 消息框架
    'django.contrib.staticfiles',  # 静态文件

    # 第三方应用
    'rest_framework',  # REST框架
    'rest_framework_simplejwt',  # JWT认证
    'rest_framework_simplejwt.token_blacklist',  # JWT黑名单
    'corsheaders',  # 跨域支持

    # 自定义应用
    'users.apps.UsersConfig',  # 用户管理
    'trend.apps.TrendConfig',  # 趋势分析
    'chat.apps.ChatConfig',  # 聊天应用
    'patent',  # 专利应用
    'dify.apps.DifyConfig',  # dify应用
    'phase_summary.apps.PhaseSummaryConfig',  # 阶段总结
    'industry_report.apps.IndustryReportConfig',  # 产业报告
    'graphNeo4j',  # Neo4j应用
    'drf_spectacular',  # API文档
    'graph.apps.GraphConfig',  # 图谱应用
    'tech_insight.apps.TechInsightConfig',  # 使用这种方式注册
]

# 中间件配置
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # 添加 CORS 中间件（必须在 CommonMiddleware 之前）
    'django.middleware.security.SecurityMiddleware',  # 安全中间件
    'django.contrib.sessions.middleware.SessionMiddleware',  # 会话中间件
    'django.middleware.common.CommonMiddleware',  # 通用中间件
    'django.middleware.csrf.CsrfViewMiddleware',  # CSRF保护
    'django.contrib.auth.middleware.AuthenticationMiddleware',  # 认证中间件
    'django.contrib.messages.middleware.MessageMiddleware',  # 消息中间件
    'django.middleware.clickjacking.XFrameOptionsMiddleware',  # 点击劫持保护
]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'task_zst',
        'USER': 'graph', 
        'PASSWORD': 'Ustack123',  
        'HOST': '10.0.219.127',
        'PORT': '3306',
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        }
    }
}
# Password validation
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'trend/output'),
]

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS设置
CORS_ALLOW_ALL_ORIGINS = True  # 允许所有来源的跨域请求
CORS_ALLOW_CREDENTIALS = True  # 允许携带认证信息

# CORS配置
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "http://10.1.60.39:5896",
]

# 允许的HTTP方法
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

# 允许的请求头
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# REST Framework settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'users.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
    ],
    'UNAUTHENTICATED_USER': None,
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

SPECTACULAR_SETTINGS = {
    'TITLE': '180项目API',
    'DESCRIPTION': '180项目API文档',
    'VERSION': '3.0.0',
    'SERVE_INCLUDE_SCHEMA': False,
    'SCHEMA_PATH_PREFIX': None,
    "SWAGGER_UI_SETTINGS": {
        "deepLinking": True,
        "persistAuthorization": True,
        "displayOperationId": True,
    },
    "SWAGGER_UI_DIST": "https://unpkg.com/swagger-ui-dist@latest",
    "SWAGGER_UI_FAVICON_HREF": "https://unpkg.com/swagger-ui-dist@latest/favicon-32x32.png",
    # 修改图标
    #"SWAGGER_UI_FAVICON_HREF": "https://xxxxx/xxxx/xxx/.png",
 }


# JWT设置
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': True,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'AUTH_HEADER_TYPES': ('',),  # 空字符串，不需要前缀
    'AUTH_HEADER_NAME': 'Authorization',  # 认证头名称
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    'TOKEN_TYPE_CLAIM': None,
    'JTI_CLAIM': None,
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'BLACKLIST_AFTER_ROTATION': True,
    # 添加以下配置
    'AUTH_COOKIE': None,  # 不使用cookie认证
    'AUTH_COOKIE_DOMAIN': None,
    'AUTH_COOKIE_SECURE': False,
    'AUTH_COOKIE_HTTP_ONLY': True,
    'AUTH_COOKIE_PATH': '/',
    'AUTH_COOKIE_SAMESITE': 'Lax',
}

# 添加自定义用户模型
AUTH_USER_MODEL = 'users.User'

# 媒体文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 添加以下配置
APPEND_SLASH = False

# 缓存设置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": f"redis://:{CACHE_REDIS_CONFIG['password']}@{CACHE_REDIS_CONFIG['host']}:{CACHE_REDIS_CONFIG['port']}/{CACHE_REDIS_CONFIG['db']}",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 100},
            "PASSWORD": CACHE_REDIS_CONFIG['password'],
        }
    }
}

# Token配置
TOKEN_EXPIRE_HOURS = 24  # token有效期（小时）
REFRESH_TOKEN_EXPIRE_DAYS = 7  # 刷新token有效期（天）

# 日志配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[{levelname}] {asctime} {module} - {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'logs/phase_summary.log',
            'formatter': 'verbose',
            'maxBytes': 1024*1024*5,  # 5MB
            'backupCount': 5,
        },
    },
    'loggers': {
        'phase_summary': {
            'handlers': ['console', 'file'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'celery_tasks': {
            'handlers': ['file'],
            'level': 'INFO',
            'propagate': True,
        },
    },
}

# 使用 Redis 作为消息代理 (broker)
CELERY_BROKER_URL = REDIS_URL
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = REDIS_URL
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60  # 设置每个任务的最大执行时间，例如30分钟
CELERY_WORKER_MAX_TASKS_PER_CHILD = 10  # 设置每个worker进程的最大任务数
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_ENABLE_UTC = False

# 会话配置
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"

# neo4j 配置
NEO4J_CONFIG = {
    "uri": "neo4j://119.254.155.85:17687",
    # "uri": "neo4j://127.0.0.1:37686",
    "user": "neo4j",
    # "password": "nbc98765"
    "password": "vPn**12@@56"
}
